﻿//日常财务 ../Stock/GetProductStock?orgCode=' + orgCode
var manager = null;
var ProjectTypeDate = [{ ProjectType: 01, text: '' }, { ProjectType: 0, text: '收入' }, { ProjectType: 1, text: '支出'}];
function addNewRow() {
            //选择产品信息 开始
    if ($("#BillState").val() == 1) { $.ligerDialog.success('已提交，不能添加！'); return; }
    var orgCode = $("#HidOrgCode").val();
    var returnValue = window.showModalDialog('../UsualFinance/SelectProductTypeItems', window, "help:No;resizable:No;status:No;scroll:yes;location:No;dialogWidth=800px;dialogHeight=500px");

    
    if (returnValue != null && returnValue != undefined) {
        //选择产品信息 结束

        var str = eval(returnValue);
        //选择产品信息 结束
        //----------------------------
      
        var billId = $("#Id").val();
        var row = manager.getSelectedRow();
        var allRows = manager.rows;
        var allLen = allRows.length;
        var tag = false;
        //参数1:rowdata(非必填)
        //参数2:插入的位置 Row Data 
        //参数3:之前或者之后(非必填)
        //----------------------------
        
        for (var i = 0; i < str.length; i++) {
            tag = false;
            var s = str[i].split(",");
            //********************************
 
            for (var k = 0; k < allLen; k++) {
                
                if (allRows[k]["Id"] == s[0]) {
                    tag = true;
                    
                    break;
                }
            }
            //********************************
            if (!tag) {
                //------------------------------------------------
                manager.addRow({
                    Id: $("#HidtempId").val(),
                    RefeID: s[0],
                    ProjectType: ProjectTypeDate[0]['ProjectType'],
                    BillState:0,
                    RefeName: s[1],
                    ProjectTypeName: "-1",//"支出",
                    OperatorName: "",
                    HandlingTime:$("#HidTempDate").val(),
                    GenerateFee: 0.0,
                    Remarks: ''
                }, row, document.getElementById("chkbefore"));
                //------------------------------------------------
            }
        }
    }
}

var columns =
            [
                  { display: 'Key', name: 'Id', type: 'text', hide: 1 },
                  { display: 'RefeID', name: 'RefeID', type: 'text', hide: 1 },
                  { display: 'ProjectType', name: 'ProjectType', type: 'text', hide: 1 },
                  { display: 'BillState', name: 'BillState', type: 'text', hide: 1 },
                  { display: '项目名称', name: 'RefeName', mintWidth: 80, width: 120, isSort: false },
                  { display: '项目类别', name: 'ProjectTypeName', mintWidth: 100, width: 140, type: 'text',
                      editor: { type: 'select', data: ProjectTypeDate, valueField: 'ProjectType' },
                      render: function (item) {
                          if (item.ProjectType != undefined && !isNaN(item.ProjectType) && parseInt(item.ProjectType) == 0) { return '收入'; }
                          return '支出';
                      }
                  },
//经办人开始
                {
                name: 'OperatorName', display: '经办人', width: 120, align: 'left', textField: 'Name'
                    , editor: {
                        type: 'popup', valueField: 'Key', textField: 'Name', grid: {
                            url: "../User/GetAllUsers",
                            parms: { orgCode: $("#HidOrgCode").val() },
                            columns: [
                                        { display: 'Key', name: 'Key', type: 'text', hide: 1 },
                                        { display: '组织机构', name: 'OrgName', mintWidth: 80, width: 120 },
                                        { display: '部门', name: 'DeptName', mintWidth: 80, width: 120 },
                                        { display: '登陆名', name: 'LoginName', mintWidth: 80, width: 120 },
                                        { display: '姓名', name: 'Name', mintWidth: 80, width: 120 }
                            ]
                        }
                        //                        , condition: {
                        //                            fields: [
                        //                            { name: 'CustomerID',type:'text',label:'客户', width: 200 }
                        //                            ]
                        //                        }
                    }
            },
//经办人结束
//  { display: '经办人', name: 'OperatorName', mintWidth: 120, width: 120, type: 'text', editor: { type: 'text'} },
                 {display: '经办时间', name: 'HandlingTime', type: 'date', format: 'yyyy-MM-dd', width: 180, editor: { type: 'date', format: 'yyyy-MM-dd'} },
                  { display: '产生费用(元)', name: 'GenerateFee', mintWidth: 80, width: 140, editor: { type: 'float'} },
                { display: '项目描述', name: 'Remark', mintWidth: 100, width: 200, editor: { type: 'text'} }
             ];

//init controls
$(document).ready(function () {
    initligerGrid();
    intiToobar();
   // $("#btnSubmit").unbind("click").bind("click", confirmOperation); //提交
    
});

function initligerGrid() {

    var wh = $(window).height();
    var fh = $("#formDiv").height();
    var gridHeight = wh - fh - 50;


    manager = $("#BillItemsGrid").ligerGrid({
        columns: columns,
      //  title: '产品发货细',//不能要标题，修改的BUG，不在ligerui.min.js文件中，所以这个BUG还是存在
        showTitle: false,
        width: '100%',
        enabledSort: true,
        enabledEdit: true,
       // height: gridHeight,
        checkbox: false,
        rownumbers: true,
        toolbar: { items: [
                                   // { text: '产品发货明细' },
                                    { text: '增加', click: addNewRow, icon: 'add' },
                                    { line: true },
                                    { text: '删除', click: deleteOperation, img: '../Content/images/delete.gif' }
                                    ]
        },
         isChecked: f_isChecked, onCheckRow: f_onCheckRow, onCheckAllRow: f_onCheckAllRow,
         url: "../UsualFinance/GetJsonOfBillDetails?billId=" + $("#Id").val() + "&rand=" + Math.random()
     });
}


//delete
function deleteOperation() {

    var row = manager.getSelectedRow();
    if (!row) { $.ligerDialog.success('请选择需要删除行！'); return; }
    $.ligerDialog.confirm('确定要删除吗？', function (yes) {
        if (yes) {
            if (row["BillState"] == 1) { $.ligerDialog.success('已提交，不能删除！'); return; }
            if (row.Id == "00000000-0000-0000-0000-000000000000") { manager.deleteSelectedRow(); return; }
            if (row.Id == null || row.Id == undefined) { alert("Id无效,无法删除"); return; }
            $.get("../UsualFinance/Delete?billId=" + $("#Id").val() + "&detailId=" + row.Id, {}, function (data) {
                manager.deleteSelectedRow();
                if (data != undefined && data == "9") {
                    initligerGrid();
                }
            });
        }
    });

//    var row = manager.getSelectedRow();
//    var ids ="";// checkedCustomer.join(',');
//    var billId = $("#Id").val();
//    var detailId = (row == undefined || row == null) ? null : row["ID"];
//    var confirmState = $("#BillState").val();
//    if (row != null && row != undefined && detailId != null && $.trim(detailId.toString()).length > 0) {
//        ids = detailId.toString() + ",";
//        $.ligerDialog.confirm('确定要删除吗？', function (yes) {
//            if (yes) {
//                if (confirmState == 0) {
//                    manager.deleteSelectedRow();
//                    if ($("#HidEmptyGuid").val() + "," != ids) {//删除非新增的
//                        $.get("../UsualFinance/DeleteItem?billId=" + billId + "&ids=" + ids, {}, function (data) {
//                            if (data != undefined && data == "9") {
//                                initligerGrid();
//                            }
//                        });
//                    }
//                }
//                else {
//                    $.ligerDialog.success('已提交，不能删除！'); return;
//                }

//            }
//        });
//    }
//    else {
//        $.ligerDialog.success('请选择需要删除行！'); return;
//    }
}


//提交
function confirmOperation() {
    var billId = $("#Id").val();
    if (billId != null && billId != undefined && $.trim(billId).length > 0) {
        $.ligerDialog.confirm('确定要提交吗？', function (yes) {
            if (yes) {
                if ($("#BillState").val() != "1") {
                    $.get("../ProductDelivery/Confirm?orgCode=" + $("#HidOrgCode").val() + "&billId=" + billId, {}, function (data) {
                        if (data != undefined && data == "9") {
                            $.ligerDialog.success('提交成功!');
                            //initligerGrid();
                            ajaxSubmitSuccess(); //公共类：提交成功后关闭当前窗口
                        }
                        else if (data == "0") {
                            $.ligerDialog.success('请先保存后再提交!');
                        }
                        else {
                            $.ligerDialog.success('系统异常!');
                        }
                    });
                } else {
                    $.ligerDialog.success('已提交，不能重复提交!');
                }
            }
        });
    }
    else {
        $.ligerDialog.success('请先保存后再提交!');
    }
}
//=========================================
function intiToobar() {
    $("#toptoolbar").ligerToolBar({ items: [
                { text: '日常财务管理' }
            ]
    });
}
//==============================

function f_onCheckAllRow(checked) {
    for (var rowid in this.records) {
        if (checked)
            addCheckedCustomer(this.records[rowid]['CustomerID']);
        else
            removeCheckedCustomer(this.records[rowid]['CustomerID']);
    }
}

/*
该例子实现 表单分页多选
即利用onCheckRow将选中的行记忆下来，并利用isChecked将记忆下来的行初始化选中
*/

var checkedCustomer = [];
function findCheckedCustomer(CustomerID) {
    for (var i = 0; i < checkedCustomer.length; i++) {
        if (checkedCustomer[i] == CustomerID) return i;
    }
    return -1;
}
function addCheckedCustomer(CustomerID) {
    if (findCheckedCustomer(CustomerID) == -1)
        checkedCustomer.push(CustomerID);
}
function removeCheckedCustomer(CustomerID) {
    var i = findCheckedCustomer(CustomerID);
    if (i == -1) return;
    checkedCustomer.splice(i, 1);
}
function f_isChecked(rowdata) {
    if (findCheckedCustomer(rowdata.CustomerID) == -1)
        return false;
    return true;
}
function f_onCheckRow(checked, data) {
    if (checked) addCheckedCustomer(data.ID);
    else removeCheckedCustomer(data.ID);
}
function f_getChecked() {
    alert(checkedCustomer.join(','));
}
